#include <clutter/clutter.h>
#include <stdlib.h>
#include <time.h>

long offset = 0;
long get_time(){
    return time(0)-offset;
}

int alpha = 0x99;

/* 刷屏的触发函数*/
void on_timeline_new_frame(ClutterTimeline * timeline, gint frame_num, gpointer data){
    static int tag = 1;
    static float step = 0;

    /*每次刷屏，转动1度*/
    step +=1.0;
    if(step >= 360)
        step = 0;
    clutter_actor_set_rotation((ClutterActor *) data,CLUTTER_X_AXIS,step,0,0,0);

    /*颜色由亮到暗，由暗到亮，循环变化*/
    if(tag == 1){
        alpha ++;
        if(alpha >= 0xef)
            tag = 0;
    }else{
        alpha --;
        if(alpha <= 0x30)
            tag ++;
    }
    ClutterColor color = {0xff,0xff,0xff,alpha};
    clutter_rectangle_set_color(CLUTTER_RECTANGLE(data),&color);
}

/* 自定义的时间触发函数，可以作为时钟函数使用，而第三个参数，经过测试应是时间片中相对时间，单位为msec */
void on_timeline_marker_reached(ClutterTimeline * timeline,gchar * marker_name, gint num,  gpointer data){
    printf("%ld marker %s reached : frame-num = %d /n", get_time(),marker_name,num);
}

int main(int argc, char* argv[]){
    ClutterColor stage_color = {0x00,0x00,0x00,0xff};
    ClutterColor rect_color = {0xff,0xff,0xff,alpha};

    clutter_init(&argc,&argv);
   
    /*Clutter stage and rect*/
    ClutterActor *stage = clutter_stage_get_default();
    clutter_actor_set_size(stage,200,200);
    clutter_stage_set_color(CLUTTER_STAGE(stage), & stage_color);
    ClutterActor * rect = clutter_rectangle_new_with_color(&rect_color);
    clutter_actor_set_size(rect,70,70);
    clutter_actor_set_position(rect,50,100);
    clutter_container_add_actor(CLUTTER_CONTAINER(stage),rect);
    clutter_actor_show(rect);
    clutter_actor_show(stage);


    offset = time(0);

    /*Timeline部分，我们开启一个时间片为5秒(5000 msecs)的timeline，并创建一个时间名为“my-mark”的时间触发点，触发点位于每个时间片的第2000毫秒。接着启动更新帧的触发事件，以便我们进行动态处理，跟着设置时间触发点的触发，我们可以在一个时间片内设置0个或者多个时间触发点。最后设置为循环模式，并且启动它。*/
    ClutterTimeline * timeline = clutter_timeline_new (5000);
    clutter_timeline_add_marker_at_time (timeline, "my-mark",2000);
    g_signal_connect(timeline,"new-frame" , G_CALLBACK(on_timeline_new_frame),rect);
    g_signal_connect(timeline,"marker-reached" , G_CALLBACK(on_timeline_marker_reached),NULL);   
    clutter_timeline_set_loop (timeline,TRUE);
    clutter_timeline_start (timeline);

    clutter_main();

    g_object_unref(timeline);
    return EXIT_SUCCESS;
} 
